package com.mrd.payClient.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Validate {
	
	/**
	 * 验证请求的有效性(参数、白名单、签名验证)
	 * @param request http请求
	 * @param params PayParams或者RefundParams
	 * @return PASS:验证通过
	 */
	public static String validateRequest(Object params){
		String result = null;
		
		//参数验证
		if(params == null){
			return "必须传入参数对象";
		}else if((result = checkParams(params)) != null){
			return result;
		}
		return result;
	}
	
	/**
	 * 参数验证(非空验证，长度验证)
	 * @return null则验证通过
	 */
	public static String checkParams(Object o){
		try {
			Field[] fields = o.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].getName();
				String firstLetter = fieldName.substring(0, 1).toUpperCase();
				String getter = "get" + firstLetter + fieldName.substring(1);
				Method method;
				method = o.getClass().getMethod(getter, new Class[] {});
				Object value = method.invoke(o, new Object[] {});
				if(value == null && "".equals(value)){
					return "参数不能为空";
				}
				if(value instanceof String && !"subject body refundReason".contains(fieldName) 
						&& ((String) value).length() > 32){
					return "参数长度过长";
				}
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
}
